package me.milo.phone.util;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

public class HttpUtil2 {
	public static byte[] getImageByteFromNet(String url) {
		byte[] data = null;
		HttpParams params = new BasicHttpParams();
		params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
		params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
		HttpClient httpClient = new DefaultHttpClient(params);
		HttpGet request = new HttpGet(url);
		ResponseHandler<byte[]> handler = getBytesResponseHandler();
		try {
			data = httpClient.execute(request, handler);
		} catch (Exception e) {
			e.printStackTrace();
			Logger.i(e.toString());
		}
		httpClient.getConnectionManager().shutdown();
		return data;
	}

	private static ResponseHandler<byte[]> getBytesResponseHandler() {
		ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
			public byte[] handleResponse(HttpResponse response) throws ClientProtocolException,
					IOException {
				StatusLine statusLine = response.getStatusLine();
				int statusCode = statusLine.getStatusCode();
				if (statusCode == HttpStatus.SC_OK) {
					HttpEntity entity = response.getEntity();
					if (entity != null) {
						return EntityUtils.toByteArray(entity);
					}
				}
				return null;
			}
		};
		return handler;
	}
}
